package com.eet.juc.pool;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 自定义线程池Demo
 *
 * @author zheng.zhang
 */
public class ThreadPoolDemo2 {

    public static void main(String[] args) {
        // AbortPolicy 抛出异常
        // CallerRunsPolicy 谁调用让谁来处理
        // DiscardPolicy 不处理超出的任务
        // DiscardOldestPolicy 和最早执行结束的线程竞争,可能竞争不成功
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(2, 5, 1, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardOldestPolicy());

        try {
            // 阻塞3 + (核心2->隶属于最大5里面的) + 最大5 = 8, 所以9的时候,阻塞队列和最大线程数都满了,这个时候就引发拒绝策略
            for (int i = 1; i <= 9; i++) {
                poolExecutor.execute(() -> System.out.println(Thread.currentThread().getName() + " 执行OK"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            poolExecutor.shutdown();
        }
    }
}
